package csv2sql;

import java.io.FileNotFoundException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.util.Scanner;

public class CSV2SQL {
	
public String takeOffQuotes(String input_str){
		
		if (input_str.startsWith("\"")){
			input_str = input_str.substring(1, input_str.length());
	    }
	    if (input_str.endsWith("\"")){
	    	input_str = input_str.substring(0, input_str.length() - 1);
	    }
	    
	    return input_str;
	}
	
	
	// parsing the result of slk commands fls + mactime
	public void parserCsv(String csvFile) throws FileNotFoundException{
		
        Connection con = null;
        PreparedStatement ps = null;
        String url = "jdbc:mysql://localhost/esercizio_2";
	    String username = "root";
	    String password = "";
        String driver = "com.mysql.jdbc.Driver";
		
		Scanner lineScan = new Scanner(csvFile);
		Scanner s = new Scanner(lineScan.nextLine());
		
		try {
            Class.forName(driver);
            con = DriverManager.getConnection(url, username, password);
            con.setAutoCommit(false);
            String query = "INSERT INTO data(fileName, size) VALUES(?, ?)";
            ps = con.prepareStatement(query);
		
		while (lineScan.hasNextLine()) {

			s = new Scanner(lineScan.nextLine());
			
			s.useDelimiter("\n");
			
			while (s.hasNext()) {
				
				String temp = s.next();
				
				String[] data = temp.split(",");
				
				String fileName = data[data.length-1];
				// take off quotes
				Integer size = Integer.valueOf(data[1]);
				//System.out.println(size);
				
				ps.setString(1, takeOffQuotes(fileName));
				ps.setDouble(2, size);
				ps.addBatch();
				
			}
		}
		
		ps.executeBatch();
		con.commit();
		ps.close();
        con.close();
		
	} catch(Exception e) {
		e.printStackTrace();
	}
	
	}
}